//
//  WXPAuthPickerView.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/28.
//

#import "WXPAuthPickerView.h"

@interface WXPAuthPickerView ()<UIGestureRecognizerDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>

@end

@implementation WXPAuthPickerView

#pragma mark - lazy
- (NSMutableArray *)markAryDatas{
    if (!_markAryDatas) {
        _markAryDatas = [NSMutableArray array];
    }
    return _markAryDatas;
}
- (UIView *)viewBack{
    if (_viewBack == nil) {
        _viewBack = [UIView new];
        _viewBack.backgroundColor = COLOR_WHITE;
        _viewBack.width = SCREEN_WIDTH;
        _viewBack.height = SCREEN_HEIGHT/3+Ratio(20);
        _viewBack.leftBottom = XY(0, SCREEN_HEIGHT);
        
        UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:_viewBack.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(16, 16)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = _viewBack.bounds;
        maskLayer.path = maskPath.CGPath;
        _viewBack.layer.mask = maskLayer;
    }
    return _viewBack;
}
- (UIButton *)btnCancelar
{
    if (_btnCancelar == nil) {
        _btnCancelar = [UIButton  new];
        _btnCancelar.widthHeight = XY(Ratio(90), BUTTON_HEIGHT);
        _btnCancelar.tag = 1;
        [_btnCancelar addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btnCancelar setTitle:@"Cancelar" forState:UIControlStateNormal];
        [_btnCancelar setTitleColor:COLOR_CONTENT forState:UIControlStateNormal];
        _btnCancelar.titleLabel.fontNum = 16;
    }
    return  _btnCancelar;
}
- (UIButton *)btnConfirmar
{
    if (_btnConfirmar == nil) {
        _btnConfirmar = [UIButton  new];
        _btnConfirmar.widthHeight = XY(Ratio(90), BUTTON_HEIGHT);
        _btnConfirmar.tag = 2;
        [_btnConfirmar addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btnConfirmar setTitle:@"Confirmar" forState:UIControlStateNormal];
        [_btnConfirmar setTitleColor:COLOR_CONTENT forState:UIControlStateNormal];
        _btnConfirmar.titleLabel.fontNum = 16;
    }
    return  _btnConfirmar;
}
- (UIView *)viewSearchBack
{
    if (_viewSearchBack == nil) {
        _viewSearchBack = [UIView  new];
        _viewSearchBack.widthHeight = XY(SCREEN_WIDTH-2*Ratio(20), BUTTON_HEIGHT);
        _viewSearchBack.hidden = true;
        _viewSearchBack.userInteractionEnabled = true;
        [_viewSearchBack addSubview:self.imageSearch];
        [_viewSearchBack addSubview:self.tfSearch];
        [_viewSearchBack addSubview:self.searchLine];
    }
    return  _viewSearchBack;
}
- (UIImageView *)imageSearch
{
    if (_imageSearch == nil) {
        _imageSearch = [UIImageView  new];
        _imageSearch.image = [UIImage imageNamed:@"icon-搜索"];
        _imageSearch.widthHeight = XY(Ratio(20), Ratio(20));
        _imageSearch.leftCenterY = XY(0, self.viewSearchBack.height/2);
    }
    return  _imageSearch;
}
- (UIView *)searchLine
{
    if (_searchLine == nil) {
        _searchLine = [UIView  new];
        _searchLine.backgroundColor = COLOR_LINE;
        _searchLine.widthHeight = XY(self.viewBack.width, 1);
        _searchLine.leftBottom = XY(0, self.viewSearchBack.height);
    }
    return  _searchLine;
}
- (UITextField *)tfSearch
{
    if (_tfSearch == nil) {
        _tfSearch = [UITextField  new];
        _tfSearch.textColor = COLOR_BLACK;
        _tfSearch.font = [UIFont systemFontOfSize:(18)];
        // 设置占位符
        NSString *placeholderText = @"HSBC México";
        UIColor *placeholderColor = [UIColor lightGrayColor]; // 自定义颜色（例如浅灰色）
        NSDictionary *attributes = @{
            NSForegroundColorAttributeName: placeholderColor // 颜色属性
        };
        NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:attributes];
        _tfSearch.attributedPlaceholder = attributedPlaceholder;
        
        
        _tfSearch.delegate = self;
        [_tfSearch addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        _tfSearch.widthHeight = XY(self.viewSearchBack.width-Ratio(10)-self.imageSearch.right-Ratio(15), BUTTON_HEIGHT-Ratio(10));
        _tfSearch.leftCenterY = XY(self.imageSearch.right+Ratio(10), self.imageSearch.centerY);
    }
    return  _tfSearch;
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [UIPickerView new];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT);
        self.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.4];
        [self addSubView];//添加子视图
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tapGestureRecognizer.delegate = self;
        tapGestureRecognizer.cancelsTouchesInView = NO;
        // [self addGestureRecognizer:tapGestureRecognizer];
    }
    return self;
}

//添加subview
- (void)addSubView{
    [self addSubview:self.viewBack];
    [self.viewBack addSubview:self.btnCancelar];
    [self.viewBack addSubview:self.btnConfirmar];
    [self.viewBack addSubview:self.viewSearchBack];
    [self.viewBack addSubview:self.pickerView];
    //初始化页面
    [self resetView];
}

#pragma mark - 手势delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.viewBack]) {
        return NO;
    }
    return YES;
}

#pragma mark - 手势点击
- (void)tapClick:(UITapGestureRecognizer * )tap{
    if(self.blockDidSelectRow){
        self.blockDidSelectRow(nil, self.viewTag);
    }
    [self removeFromSuperview];
}

#pragma mark - 收键盘
// 点击界面空白区域 收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}
// return键收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 实现监听方法
- (void)textFieldDidChange:(UITextField *)textField{
    NSLog(@" --- :%@",textField.text);
    NSMutableArray * array = [NSMutableArray new];
    
//    if (range.location != NSNotFound) {
//        NSLog(@"字符串包含子字符串 %@ (不区分大小写)", substringToSearch);
//    } else {
//        NSLog(@"字符串不包含子字符串 %@ (不区分大小写)", substringToSearch);
//    }
//
//
    
    if(isStr(textField.text)){
        for (ModelBtn * model in self.markAryDatas) {
            NSRange range = [model.title rangeOfString:textField.text options:NSCaseInsensitiveSearch];
            if (range.location != NSNotFound) {
                [array addObject: model];
            }
        }
        [self.aryDatas removeAllObjects];
        [self.aryDatas addObjectsFromArray:array];
    }else{
        [self.aryDatas removeAllObjects];
        [self.aryDatas addObjectsFromArray:self.markAryDatas];
    }
    self.selectModel = self.aryDatas.firstObject;
    [self.pickerView selectRow:0 inComponent:0 animated:true];
    [self.pickerView reloadAllComponents];
}


#pragma mark - 点击事件
- (void)btnClick:(UIButton *)sender{
    switch (sender.tag) {
        case 1:
        {
            if(self.blockDidSelectRow){
                self.blockDidSelectRow(nil, self.viewTag);
            }
            [self removeFromSuperview];
        }
            break;
        case 2:
        {
            if(self.blockDidSelectRow){
                self.blockDidSelectRow(self.selectModel, self.viewTag);
            }
            [self removeFromSuperview];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 刷新view
- (void)resetView{
    self.btnCancelar.leftTop = XY(0, Ratio(6));
    self.btnConfirmar.rightCenterY = XY(SCREEN_WIDTH, self.btnCancelar.centerY);
    
    self.pickerView.widthHeight = XY(SCREEN_WIDTH, self.viewBack.height-Ratio(20)-self.btnCancelar.bottom);
    self.pickerView.leftTop = XY(0, self.btnConfirmar.bottom);
}
- (void)resetViewWithIsShowSearch:(BOOL)isShowSearch{
    [self resetView];
    
    self.viewSearchBack.hidden = !isShowSearch;
    self.viewSearchBack.centerXTop = XY(self.viewBack.width/2, self.btnCancelar.bottom);

    self.pickerView.leftTop = XY(0, self.viewSearchBack.bottom);
    
    self.viewBack.height = self.pickerView.bottom+Ratio(20);
    UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:self.viewBack.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(16, 16)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.viewBack.bounds;
    maskLayer.path = maskPath.CGPath;
    self.viewBack.layer.mask = maskLayer;
    self.viewBack.leftBottom = XY(0, SCREEN_HEIGHT);
}

- (void)resetViewWithAry:(NSMutableArray *)aryDatas withTag:(NSInteger)tag{
    [self.markAryDatas removeAllObjects];
    [self.markAryDatas addObjectsFromArray:aryDatas];
    
    self.viewTag = tag;
    self.aryDatas = aryDatas;
    self.selectModel = self.aryDatas.firstObject;
    [self.pickerView selectRow:0 inComponent:0 animated:true];
    [self.pickerView reloadAllComponents];
}

#pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.aryDatas.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return BUTTON_HEIGHT;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *customLabel = (UILabel *)view;
    if (!customLabel) {
        customLabel = [[UILabel alloc] init];
        customLabel.textAlignment = NSTextAlignmentCenter;
        [customLabel setFont:[UIFont systemFontOfSize:(17)]];
    }
    ModelBtn * model = self.aryDatas[row];
    customLabel.text = model.title;
    customLabel.textColor = COLOR_BLACK;
    return customLabel;
}

// 返回列表的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    NSLog(@" --- select row --- %ld",row);
    return  self.aryDatas[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//    NSLog(@" --- select row --- %ld",row);
    if(row<self.aryDatas.count){
        self.selectModel = self.aryDatas[row];
    }
}

@end
